package com.jmlee.controller;

import com.jmlee.cache.AdminCache;
import com.jmlee.component.CaptchaComp;
import com.jmlee.component.HostHolder;
import com.jmlee.exception.Asserts;
import com.jmlee.pojo.CommonResult;
import com.jmlee.pojo.Role;
import com.jmlee.service.*;
import com.jmlee.util.SecurityUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * @Description 登录注册相关入口控制器
 * @Author jmLee
 * @Date 2021/3/4 14:18
 * @Version 1.0
 */
@Controller
public class LoginController {

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Autowired
    private CaptchaComp captchaComp;

    @Autowired
    private HostHolder hostHolder;

    /**
     * 记住我登录凭证超时时间
     */
    public int REMEMBER_EXPIRED_SECONDS = 3600 * 24 * 100;
    /**
     * 默认状态的登录凭证超时时间：12h
     */
    public int DEFAULT_EXPIRED_SECONDS = 3600 * 12;



    @Autowired
    private AdminCache adminCache;

    @Autowired
    private AdminService adminService;

    @Autowired
    private MenuService menuService;

    @Autowired
    private RoleService roleService;


    /**
     * 动态菜单
     * @param
     * @return
     */
    @GetMapping("/menu")
    @ResponseBody
    public CommonResult<Map<String, Object>> getMenu() {
        Long roleId = hostHolder.getAdmin().getRoleId();
//        System.out.println("用户角色ID" + roleId);

        Map<String, Object> allMenuInfo = menuService.getMenuInfo(roleId);
        return CommonResult.success(allMenuInfo, "ok");
    }

    /**
     * 角色列表
     * @return
     */
    @GetMapping("/role")
    @ResponseBody
    public CommonResult<List<Role>> getRoleList(){
        List<Role> roleList = roleService.roleList();
        return CommonResult.success(roleList,"200");
    }

    @GetMapping(path = {"","/login"})
    public String getLoginPage() {

        return "login";
    }

    @PostMapping("/login")
    @ResponseBody
    public CommonResult login(String username,
                              String password,
                              String authCode,
                              Boolean rememberMe,
                              @CookieValue("captchaOwner") String captchaOwner,
                              HttpServletResponse resp) {

        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            Asserts.fail("用户名或密码不能为空！");
        }

        if (StringUtils.isBlank(captchaOwner)) {
            return CommonResult.failed("验证码已过期，请点击图片刷新");
        }

        String authCode1 = adminCache.getAuthCode(captchaOwner);
        if (StringUtils.isBlank(authCode1) || StringUtils.isBlank(authCode) || !authCode.equalsIgnoreCase(authCode1)) {
            return CommonResult.failed("验证码错误");
        }
        // 对密码加密
        password = SecurityUtil.getMD5(password);

        int expiredSeconds = (rememberMe != null ? REMEMBER_EXPIRED_SECONDS : DEFAULT_EXPIRED_SECONDS);

        Map<String, Object> map = adminService.login(username, password, expiredSeconds);

        if (map.containsKey("ticket")) {
            // 一旦登录成功后才生成登录凭证，并保存到浏览器Cookie中
            Cookie cookie = new Cookie("ticket", map.get("ticket").toString());
            // 设置Cookie的有效范围
            cookie.setPath(contextPath);
            // 设置Cookie的有效时间
            cookie.setMaxAge(expiredSeconds);
            resp.addCookie(cookie);

            return CommonResult.success(null, "登录成功");
        } else {
            return CommonResult.failed(String.valueOf(map.get("fail")));
        }
    }


    /**
     * 生成验证码
     *
     * @param response
     * @throws Exception
     */
    @GetMapping("/captcha")
    public void captcha(HttpServletResponse response) throws Exception {

        captchaComp.out(response);
    }


    @GetMapping("/index")
    public String index() {
        return "index";
    }

    @GetMapping("/logout")
    @ResponseBody
    public String logout(@CookieValue("ticket") String ticket) {

        adminService.logout(ticket);
        return "logout";
    }


    @GetMapping("/welcome")
    public String welcome(){
        return "welcome";
    }

//    @GetMapping("/welcomeImage")
//    public String welcomeImage(){
//        return "redirect:/static/images/background/welcome.jpg";
//    }

}
